package com.kt.silenceinstalldemo

import java.io.File
/**
 * @Author Xzh
 * @Date 2025/1/24
 * @Description
 * 这个工具类包含几种常见的检查方法来确定设备是否已 root。
 */
object RootChecker {

    // 检查常见的 root 二进制文件
    private val rootBinaries = arrayOf(
        "/system/bin/su",
        "/system/xbin/su",
        "/system/app/Superuser.apk",
        "/sbin/su",
        "/system/bin/.ext/.su",
        "/system/usr/we-need-root/su-backup",
        "/system/xbin/mu"
    )

    // 检查设备是否已 root
    fun isDeviceRooted(): Boolean {
        return checkRootBinaries() || checkRootAccess() || checkSUCommand()
    }

    // 检查常见的 root 二进制文件是否存在
    private fun checkRootBinaries(): Boolean {
        for (path in rootBinaries) {
            if (File(path).exists()) {
                return true
            }
        }
        return false
    }

    // 尝试执行 su 命令
    private fun checkSUCommand(): Boolean {
        try {
            Runtime.getRuntime().exec("su")
            return true
        } catch (e: Exception) {
            return false
        }
    }

    // 检查是否具有 root 访问权限
    private fun checkRootAccess(): Boolean {
        return try {
            val process = Runtime.getRuntime().exec(arrayOf("/system/xbin/which", "su"))
            val exitValue = process.waitFor()
            exitValue == 0
        } catch (e: Exception) {
            false
        }
    }
}